package ru.java4java.utils;

import java.io.*;

public class SerializationUtils {

    public static Object objectFromBytes(byte[] data) throws IOException, ClassNotFoundException {
        ByteArrayInputStream stream = new ByteArrayInputStream(data);
        ObjectInputStream reader = new ObjectInputStream(stream);
        return reader.readObject();
    }

    public static byte[] objectAsBytes(Serializable object) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        try {
            ObjectOutputStream writer = new ObjectOutputStream(stream);
            writer.writeObject(object);
        } catch (IOException ignored) {}
        return stream.toByteArray();
    }

    private void objectAsBytes(InputStream stream) {

    }

    public static boolean isSerializationProtocol(byte[] data) {
        int b1 = data[0];
        int b2 = data[1];
        return b1 == 0xAC && b2 == 0xED;
    }

    public static int getSerializationVersion(byte[] data) {
        int b1 = data[2];
        int b2 = data[3];
        return ByteUtils.createUnsignedShort(b1, b2);
    }

    public static int getClassNameLength(byte[] data) {
        int b1 = data[6];
        int b2 = data[7];
        return ByteUtils.createUnsignedShort(b1, b2);
    }

    public static String getClassName(byte[] data) {
        int end = getClassNameLength(data) + 8;
        StringBuilder sb = new StringBuilder();
        for (int i = 8; i < end; i += 2) {
            sb.append(ByteUtils.createChar(data[i], data[i + 1]));
        }
        return sb.toString();
    }

    public static long getSerialVersionUID(byte[] data) {
        int offset = getClassNameLength(data) + 8;
        return ByteUtils.getLong(data, offset);
    }
}
